package com.bkd.dreams.server.core;

import javax.jdo.PersistenceManager;

import com.bkd.dreams.client.event.service.VolunteerEventService;
import com.bkd.dreams.client.login.NotLoggedInException;
import com.bkd.dreams.client.stand.StandRole;
import com.bkd.dreams.server.PMF;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public abstract class RemoteServiceImpl extends RemoteServiceServlet {

	public RemoteServiceImpl() {
		super();
	}

	public RemoteServiceImpl(Object delegate) {
		super(delegate);
	}

	protected void checkLoggedIn() throws NotLoggedInException {
		if (getUser() == null) {
			throw new NotLoggedInException("Not logged in.");
		}
	}

	protected User getUser() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.getCurrentUser();
	}

	protected void store(Object obj) throws NotLoggedInException {
		checkLoggedIn();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(obj);
		} finally {
			pm.close();
		}
	}

	protected void removeByKey(String key) throws NotLoggedInException {
		checkLoggedIn();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StandRole obj = pm.getObjectById(StandRole.class, key);
			pm.deletePersistent(obj);
		} finally {
			pm.close();
		}
	}

}